/*
 * Copyright (C) 2008  Wang Hoi <fearee@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
*/
#include "http_source.h"
#include <QtGlobal>

#define HEADER_LENGTH 84
/*
HTTP/1.0 200 OK
Content-type: application/octet-stream
Cache-Control: no-cache

*/
HttpSource::HttpSource(const QString &addr): buf()
{
    hostname = addr.left(addr.lastIndexOf(':'));
    port = addr.right(addr.size() - addr.lastIndexOf(':') - 1).toUShort();
}
HttpSource::~HttpSource()
{
}
void HttpSource::init()
{
    header_len = HEADER_LENGTH;
    req.clear();
    req.append("GET / HTTP/1.1 \r\n");
    req.append("User-Agent: Livercaster/0.1 \r\n");
    req.append("Accept: */* \r\n");
    req.append("Host: " + hostname + ':' + QByteArray::number(port) + " \r\n");
    req.append("Connection: Keep-Alive \r\n\r\n");
    socket.connectToHost(hostname, port);
    connect(&socket, SIGNAL(readyRead()),
            SLOT(onReadyRead()));
    connect(&socket, SIGNAL(connected()),
            SLOT(onConnected()));
    connect(&socket, SIGNAL(disconnected()),
            SLOT(onDisconnected()));
    QTimer::singleShot(2000, this, SLOT(onTimer()));
}
void HttpSource::onReadyRead()
{
    int strip_len;
    buf = socket.readAll();
    if ((buf.size() > 0) && (header_len > 0)) {
        strip_len = qMin(header_len, buf.size());
        buf.remove(0, strip_len);
        header_len -= strip_len;
    }
    if (buf.size() > 0) {
        emit dataGot(buf);
    }
}
void HttpSource::onDisconnected()
{
    qDebug() << "Source disconnected";
    emit reset();
    QTimer::singleShot(2000, this, SLOT(onTimer()));
}
void HttpSource::onConnected()
{
    qDebug() << "Source connected";
    socket.write(req);
}
void HttpSource::onError()
{
    qWarning() << QString("Source Error--%1").arg(socket.errorString());
    socket.disconnectFromHost();
}
void HttpSource::onTimer()
{
    if (socket.state() == QAbstractSocket::UnconnectedState) {
        socket.connectToHost(hostname, port);
        QTimer::singleShot(2000, this, SLOT(onTimer()));
    }
}
#include "http_source.moc"
